import {
  defineComponent,
  nextTick,
  onMounted,
  onUnmounted,
  ref,
  watch,
} from 'vue';
import './monaco-editor.scss';
import {
  getCodeProps,
  getEditorEmits,
  useNamespace,
} from '@ibiz-template/vue3-util';
import * as monaco from 'monaco-editor';
import loader from '@monaco-editor/loader';
import { CodeEditorController } from '../code-editor.controller';
import { useUIStore } from '../../../util';

export const IBizCode = defineComponent({
  name: 'IBizCode',
  props: getCodeProps<CodeEditorController>(),
  emits: getEditorEmits(),
  setup(props, { emit }) {
    const ns = useNamespace('code');

    const currentVal = ref<string>('');

    let editor: monaco.editor.IStandaloneCodeEditor;
    let monacoEditor: typeof monaco.editor;
    const { UIStore } = useUIStore();

    // 编辑器主题
    const getMonacoTheme = (name: string): string => {
      return name === 'dark' ? `vs-${UIStore.theme}` : 'vs'; // 官方自带三种主题vs, hc-black, or vs-dark
    };

    watch(
      () => UIStore.theme,
      newVal => {
        monacoEditor.setTheme(getMonacoTheme(newVal));
      },
    );

    watch(
      () => props.value,
      newVal => {
        if (newVal !== currentVal.value) {
          currentVal.value = newVal || '';
          editor?.setValue(currentVal.value);
        }
      },
      { immediate: true },
    );

    const codeEditBox = ref();

    const editorInit = (): void => {
      nextTick(() => {
        loader.config({
          paths: {
            vs: `${ibiz.env.pluginBaseUrl}/monaco-editor@0.41.0/min/vs`,
          },
        });
        loader.init().then(loaderMonaco => {
          // 初始化编辑器
          if (!editor) {
            monacoEditor = loaderMonaco.editor;
            editor = loaderMonaco.editor.create(codeEditBox.value, {
              language: props.language || props.controller.language, // 语言支持自行查阅demo
              theme: getMonacoTheme(UIStore.theme),
              foldingStrategy: 'indentation',
              renderLineHighlight: 'all', // 行亮
              selectOnLineNumbers: true, // 显示行号
              minimap: {
                enabled: true,
              },
              readOnly: false, // 只读
              fontSize: 16, // 字体大小
              scrollBeyondLastLine: false, // 取消代码后面一大段空白
              overviewRulerBorder: false, // 不要滚动条的边框
            });
            setTimeout(() => {
              editor.layout();
            });
          } else {
            editor.setValue('');
          }

          // 监听值的变化
          editor.onDidChangeModelContent(() => {
            currentVal.value = editor.getValue();
            emit('change', currentVal.value);
          });

          window.addEventListener('resize', () => {
            editor.layout();
          });
        });
      });
    };

    onMounted(() => {
      editorInit();
    });

    onUnmounted(() => {
      editor?.dispose();
    });

    return { ns, currentVal, codeEditBox };
  },
  render() {
    return <div ref='codeEditBox' class={this.ns.b()}></div>;
  },
});
